import { forwardRef, useState, useImperativeHandle, createElement } from 'react';
import ResizableDrawer from './common/ResizableDrawer';
import { getNodeForm } from './node-form';
import useFlowStore from '../hooks/flowStore';

const EditNodeDrawer = (_, ref) => {
  const [visible, setVisible] = useState(false);
  const [openParams, setOpenParams] = useState(null);
  const [currentNodeForm, setCurrentNodeForm] = useState(null);
  const [currentData, setCurrentData] = useState(null);
  const flowContext = useFlowStore();

  useImperativeHandle(ref, () => ({
    open: open,
  }));

  const open = (params) => {
    setVisible(true);
    setOpenParams(params);
    // setCurrentNodeForm(getNodeForm(params.data.elementType));
    setCurrentData(params.data);
  };

  const onUpdate = (val) => {
    flowContext.update((draft) => {
      const index = draft.flowContent.findIndex((item) => item.key === val.key);
      if (index > -1) {
        Object.assign(draft.flowContent[index], val);
      }
    });
    setVisible(false);
    openParams.afterEdit(currentData);
  };

  const onClosed = () => {
    setCurrentNodeForm(null);
  };

  const MethodForm = getNodeForm('METHOD')

  return (
    <ResizableDrawer
      open={visible}
      onClose={() => setVisible(false)}
      size={560}
      title={currentData?.name}
      onClosed={onClosed}
      drawerKey="FLOW_NODE"
    >
      {getNodeForm(openParams?.data?.elementType) && (
        createElement(getNodeForm(openParams.data.elementType), {
          data: currentData,
          onUpdate: onUpdate,
          onCancel: () => setVisible(false)
        })
      )}
    </ResizableDrawer>
  );
};

export default forwardRef(EditNodeDrawer); 